//
// Created by Administrator on 2020/9/18.
//

#include <string>
#include <cstring>
#include "stun_attribute.h"

using namespace std;

StunAttribute::StunAttribute()
    :attr_type_(0)
    ,attr_length_(0)
    ,attr_value_(nullptr)
{

}

StunAttribute::StunAttribute(uint16_t type)
    :attr_type_(type)
    ,attr_length_(0)
    ,attr_value_(nullptr)
{
}

StunAttribute::StunAttribute(uint16_t type, uint16_t length)
    : attr_type_(type)
    , attr_length_(length)
{
    attr_value_ = new uint8_t[length];
}

StunAttribute::StunAttribute(const StunAttribute& rhs)
    : attr_type_(rhs.attr_type_)
    , attr_length_(rhs.attr_length_)
{
    memcpy(attr_value_, rhs.attr_value_, attr_length_);
}

//StunAttribute& StunAttribute::operator=(const StunAttribute& rhs){
//    if(rhs != this){
//        attr_type_ = rhs.attr_type_;
//        attr_length_ = rhs.attr_length_;
//        memcpy(attr_value_, rhs.attr_value_, rhs.attr_length_);
//    }
//}

StunAttribute::~StunAttribute() {
    delete  attr_value_;
}

void StunAttribute::set_type(const uint16_t& attr_type){
    attr_type_ = attr_type;
}

uint16_t StunAttribute::get_type() const{
    return attr_type_;
}

void StunAttribute::set_value(uint8_t* value, uint16_t& length){
    memcpy(attr_value_, value, attr_length_);
}

uint8_t* StunAttribute::get_value() const{
    return  attr_value_;
}

bool StunAttribute::parse(const char* buffer, uint16_t length){

    memcpy((void*)&attr_type_, buffer, 2);
    attr_type_ = ntoh16(attr_type_);

    memcpy((void*)&attr_length_, buffer, 2);
    attr_length_ = ntoh16(attr_length_);

    memcpy((void*)&attr_value_,buffer+4, attr_length_);

    return true;
}

uint16_t StunAttribute::encode(char* buffer, uint16_t){
    buffer = encode16(buffer, attr_type_);
    buffer = encode16(buffer, attr_length_);
    memcpy(buffer+4, attr_value_, attr_length_);
    return attr_length_;
}

char* StunAttribute::encode16(char* buf, uint16_t data){
    uint16_t ndata = ntoh16(data);
    memcpy(buf, reinterpret_cast<void*>(&ndata), sizeof(uint16_t));
    return buf + sizeof(uint16_t);

}

char* StunAttribute::encode32(char* buf, uint32_t data){
    uint32_t ndata = ntoh16(data);
    memcpy(buf, reinterpret_cast<void*>(&ndata), sizeof(uint32_t));
    return buf + sizeof(uint32_t);
}



